/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package canary;

import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.saas.RestResponse;
import org.netbeans.saas.twitter.TwitterWhatAreYouDoingService;
import twitter.whatareyoudoingservice.twitterresponse.DirectMessageType;
import twitter.whatareyoudoingservice.twitterresponse.DirectMessages;
import twitter.whatareyoudoingservice.twitterresponse.StatusType;
import twitter.whatareyoudoingservice.twitterresponse.Statuses;

/**
 *
 * @author hulles
 */
public class TwitterUtils {
    private final static boolean LOGERRORS = false;
    
    public TwitterUtils() {
    }
    
    @SuppressWarnings("unchecked")
    public List<StatusType> getFriendsStatus (String sinceID) {
        RestResponse result = null;
        List<StatusType> statusList;
        Statuses resultObj;
        String since = null;
        String page = "1";
        String format = "xml";
        
        statusList = Collections.EMPTY_LIST;
        try {
             result = TwitterWhatAreYouDoingService.getFriendsTimeline(since, sinceID, page, format);
             resultObj = result.getDataAsObject(Statuses.class);
             statusList = resultObj.getStatus();
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            statusList = null;
        }
        return statusList;
    }
    
    @SuppressWarnings("unchecked")
    public List<StatusType> getArchive (String page) {
        RestResponse result = null;
        List<StatusType> statusList;
        Statuses resultObj;
        String since = null;
        String sinceID = null;
        String format = "xml";
        
        statusList = Collections.EMPTY_LIST;
        try {
             result = TwitterWhatAreYouDoingService.getUserTimeline(since, sinceID, page, format);
             resultObj = result.getDataAsObject(Statuses.class);
             statusList = resultObj.getStatus();
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            statusList = null;
        }
        return statusList;
    }
    
    @SuppressWarnings("unchecked")
    public List<StatusType> getReplies(String sinceID) {
        RestResponse result = null;
        List<StatusType> statusList;
        Statuses resultObj;
        String since = null;
        String page = "1";
        String format = "xml";
        
        statusList = Collections.EMPTY_LIST;
        try {
             result = TwitterWhatAreYouDoingService.getReplies(since, sinceID, page, format);
             resultObj = result.getDataAsObject(Statuses.class);
             statusList = resultObj.getStatus();
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            statusList = null;
        }
        return statusList;
    }

    @SuppressWarnings("unchecked")
    public List<DirectMessageType> getDirectMsgs(String sinceID) {
        RestResponse result = null;
        List<DirectMessageType> msgList;
        DirectMessages resultObj;
        String since = null;
        String page = "1";
        String format = "xml";
        
        msgList = Collections.EMPTY_LIST;
        try {
             result = TwitterWhatAreYouDoingService.getDirectMessagesToMe(since, sinceID, page, format);
             resultObj = result.getDataAsObject(DirectMessages.class);
             msgList = resultObj.getDirectMessage();
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            msgList = null;
        }
        return msgList;
    }

    public RestResponse updateStatus(String status) {
        String format = "xml";
        RestResponse result;
        
        try {
             result = TwitterWhatAreYouDoingService.updateStatus(status, format);
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            result = null;
        }
        return result;
    }
    
    public RestResponse verifyLogin() {
        String format = "xml";
        RestResponse result;
        
        try {
             result = TwitterWhatAreYouDoingService.verifyCredentials(format);
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            result = null;
        }
        return result;
    }
    
    public void signOut() {
        try {
            TwitterWhatAreYouDoingService.endSession();
        } catch (Exception ex) {
            if (LOGERRORS) {
                Logger.getLogger(TwitterUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public static String tweetToHTML(String text) {
        String[] splitText;
        StringBuffer sBuf;
        
        sBuf = new StringBuffer();
        splitText = text.split(" ");
        for (String s : splitText) {
            if (sBuf.length() > 0) {
                sBuf.append(" ");
            }
            if (s.startsWith("http://")) {
                sBuf.append("<a href='");
                sBuf.append(s);
                sBuf.append("'>");
                sBuf.append(s);
                sBuf.append("</a>");
            } else if (s.startsWith("@") && (s.length() > 1)) {
                // doesn't check for malformed urls...
                sBuf.append("<a href='");
                sBuf.append("http://twitter.com/" + s.substring(1));
                sBuf.append("'>@"); // follow twitter format, @ is not part of link
                sBuf.append(s.substring(1));
                sBuf.append("</a>");
            } else {
                sBuf.append(s);
            }
        }
        return sBuf.toString();
    }
    
/*  Return codes (from Twitter API):   
    * 200 OK: everything went awesome.
    * 304 Not Modified: there was no new data to return.
    * 400 Bad Request: your request is invalid, and we'll return an error message that tells you why. This is the status code returned if you've exceeded the rate limit (see below). 
    * 401 Not Authorized: either you need to provide authentication credentials, or the credentials provided aren't valid.
    * 403 Forbidden: we understand your request, but are refusing to fulfill it.  An accompanying error message should explain why.
    * 404 Not Found: either you're requesting an invalid URI or the resource in question doesn't exist (ex: no such user). 
    * 500 Internal Server Error: we did something wrong.  Please post to the group about it and the Twitter team will investigate.
    * 502 Bad Gateway: returned if Twitter is down or being upgraded.
    * 503 Service Unavailable: the Twitter servers are up, but are overloaded with requests.  Try again later.
*/
    public static String requestResponse(RestResponse response) {
        String responseString;
        
        if (response.getResponseCode() == 200) {
            responseString = null;
        } else {
            responseString = response.getResponseMessage();
        }
        return responseString;
    }
}
